package com.mozmob.visa;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.TimerTask;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

public class VisaTask extends TimerTask {

	public static final String VISA_URL = "http://www.visto-eua.com.br/agendamento-web/tempoEsperaAgendamento.do?paginaInicial=1";

	private VisaVaga visaVaga;
	
	public VisaTask(VisaVaga visaVaga) {
		this.visaVaga = visaVaga;
	}
	
	public void run() {
		try {
			String html = readHTML(VISA_URL);
			foundDay(html);
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	private boolean foundDay(String html) {
		html = html.substring(html.indexOf("<table class=\"tabela_sublinha_fundo\" width=\"100%\">"));
		
		boolean found = false;
		Pattern cityPattern = Pattern.compile("<td width=\"20%\">(.*?)</td>");
		Pattern datePattern = Pattern.compile("<td width=\"50%\">(.*?)</td>");
		Pattern waitPattern = Pattern.compile("<td align=\"center\" width=\"30%\">(.*?)</td>");
		
		Matcher cityMatch = cityPattern.matcher(html);
		Matcher dateMatch = datePattern.matcher(html);
		Matcher waitMatch = waitPattern.matcher(html);
		String city = "";
		String date = "";
		String wait = "";
		
		while(cityMatch.find()){
			dateMatch.find();
			waitMatch.find();
			
			city = cityMatch.group().replaceFirst("<td width=\"20%\">", "").replaceFirst("</td>", "").trim();
			date = dateMatch.group().replaceFirst("<td width=\"50%\">", "").replaceFirst("</td>", "").trim();
			wait = waitMatch.group().replaceFirst("<td align=\"center\" width=\"30%\">", "").replaceFirst("</td>", "").trim();
			wait = wait.substring(0, wait.toLowerCase().indexOf("d") - 1);

			this.visaVaga.updateConsulate(city, date, Integer.parseInt(wait));
		}
		
		return found;
	}	

	private String readHTML(String url) throws ClientProtocolException, IOException {
		HttpClient client = new DefaultHttpClient();
		HttpGet request = new HttpGet(url);
		HttpResponse response = client.execute(request);

		InputStream in = response.getEntity().getContent();
		BufferedReader reader = new BufferedReader(new InputStreamReader(in, "iso-8859-1"));
		StringBuilder str = new StringBuilder();
		String line = null;
		while ((line = reader.readLine()) != null) {
			str.append(line);
		}
		reader.close();
		in.close();
		return str.toString();
	}
	
}
